﻿using System;
using System.Web;
using System.Configuration;
using Facebook.Rest;
using Facebook.Session;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ConnectAuthentication.isConnected())
        {
            ConnectSession connectSession = new ConnectSession(
                ConnectAuthentication.ApiKey, 
                ConnectAuthentication.SecretKey);

            Api api = new Api(connectSession);
            
            //Display user data captured from the Facebook API.

            Facebook.Schema.user user = api.Users.GetInfo();
            string fullName = user.first_name + " " + user.last_name;

            lblName.Text = fullName;
        }
        else
        {
            //Facebook Connect not authenticated, proceed as usual.
            
        }
    }
}

public class ConnectAuthentication
{
    public ConnectAuthentication()
    {

    }

    public static bool isConnected()
    {
        return (SessionKey != null && UserID != -1);
    }

    public static string ApiKey
    {
        get
        {
            return ConfigurationManager.AppSettings["APIKey"];
        }
    }

    public static string SecretKey
    {
        get
        {
            return ConfigurationManager.AppSettings["Secret"];
        }
    }

    public static string SessionKey
    {
        get
        {
            return GetFacebookCookie("session_key");
        }
    }

    public static int UserID
    {
        get
        {
            int userID = -1;
            int.TryParse(GetFacebookCookie("user"), out userID);
            return userID;
        }
    }

    private static string GetFacebookCookie(string cookieName)
    {
        string retString = null;
        string fullCookie = ApiKey + "_" + cookieName;

        if (HttpContext.Current.Request.Cookies[fullCookie] != null)
            retString = HttpContext.Current.Request.Cookies[fullCookie].Value;

        return retString;
    }
}
